package com.lhq.plugin.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.MultiPageEditorPart;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.wst.sse.ui.StructuredTextEditor;


public abstract class BaseHandler extends AbstractHandler {

    public ITextEditor getTextEditor() {
        IEditorPart iep = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
        ITextEditor ite = null;
        if (iep instanceof ITextEditor) {
            ite = (ITextEditor) iep;
        } else if (iep instanceof MultiPageEditorPart) {
            MultiPageEditorPart part = (MultiPageEditorPart) iep;
            Object sp = part.getSelectedPage();
            if (sp instanceof StructuredTextEditor) {
                ite = (StructuredTextEditor) sp;
            }
        }
        return ite;
    }

    public TextSelection getTextSelection(ITextEditor ite) {
        if (ite == null) {
            return null;
        }
        ISelectionProvider isp = ite.getSelectionProvider();
        ISelection selection = isp.getSelection();
        if (selection instanceof TextSelection) {
            return (TextSelection) selection;
        }
        return null;
    }

    public IDocument getDocument(ITextEditor ite) {
        if (ite == null) {
            return null;
        }
        return ite.getDocumentProvider().getDocument(ite.getEditorInput());
    }

    public IViewPart getViewPart(ITextEditor ite, String viewName) {
        if (ite == null) {
            return null;
        }
        return ite.getSite().getPage().findView(viewName);
    }

    public String getSelectText(IViewPart viewPart) {
        if (viewPart == null) {
            return null;
        }

        ISelection selection = viewPart.getViewSite().getSelectionProvider().getSelection();
        if (selection instanceof TextSelection) {
            return ((TextSelection) selection).getText();
        }
        return null;
    }

    public String getSelectText(IDocument document, TextSelection selection) {
        if (document == null || selection == null) {
            return null;
        }
        String text = document.get();
        int offSet = selection.getOffset();
        int length = selection.getLength();
        if (text == null || offSet < 0 || length < 1) {
            return null;
        }
        return text.substring(offSet, offSet + length);
    }
}
